package com.liu.filter;

import com.alibaba.fastjson.JSONObject;
import com.liu.pojo.Result;
import com.liu.utils.JwtUtils;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@WebFilter(urlPatterns = "/*")
public class DemoFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
                Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        String url = req.getRequestURL().toString();
        log.info("请求的url为：{}",url);
        if(url.contains("/login")){
            log.info("登录操纵放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String jwt = req.getHeader("token");
        if(!StringUtils.hasLength(jwt)){
            log.info("jwt为空，返回未登录信息");
            Result result = Result.error("NO_LOGIN");
            String noLogin = JSONObject.toJSONString(result);
            //设置HTTP响应码
            res.setStatus(HttpStatus.SC_OK);
            res.getWriter().write(noLogin);
            return;
        }
        log.info("jwt令牌为：{}",jwt);
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            log.info("令牌解析失败，返回错误令牌提示");
            Result result = Result.error("ERROR_JWT");
            String errorJwt = JSONObject.toJSONString(result);
            res.setStatus(HttpStatus.SC_OK);
            res.getWriter().write(errorJwt);
            return;
        }
        log.info("令牌合法，放行");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
